'use strict'

const auth = require('../tools/auth');

let fs = require('fs'),
    path = require('path'),
    router = require('koa-router')();

function findJs(filesPath) {
    let files = fs.readdirSync(filesPath);
    let real = files.filter(x => {
        return x.endsWith('.js') && x !== "index.js"
    })
    return real;
}

function registry(files, item) {
    files.forEach(element => {
        let filePath = path.join(item, element);
        let router_fn = require(filePath);
        for (let x in router_fn) {
            let arr = router_fn[x];
            let type = router_fn[x][0];
            if (type === 'get') {
                if (arr.length === 2) {
                    let fn = arr[1];
                    router.get(x, fn);
                } else {
                    let auth = arr[1]
                    let fn = arr[2];
                    router.get(x, auth, fn);
                }
            } else {
                if (arr.length === 2) {
                    let fn = arr[1];
                    router.post(x, fn);
                } else {
                    let auth = arr[1]
                    let fn = arr[2];
                    router.post(x, auth, fn);
                }
            }
        };
    })
}

module.exports = function(dir) {
    let workDir = dir || 'control';
    let workPath = path.resolve('.');
    let realRouter = path.join(workPath, workDir);
    let jsFile = findJs(realRouter);
    registry(jsFile, realRouter);
    return router.routes();
}